#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#include "temperdbs.h"
#include "pjson.h"



typedef void *(THREAD_BODY) (void *thread_arg);



int thread_start(pthread_t * thread_id,THREAD_BODY * thread_workerbody,void *thread_arg)
{

	int             rv=-1;
	pthread_attr_t  thread_attr;

	if(pthread_attr_init(&thread_attr))
	{
		printf("pthread_attr_init() failure:%s\n",strerror(errno));
		goto CleanUp;
	}

	if(pthread_attr_setstacksize(&thread_attr,120*1024))
	{
		printf("pthread_attr_setstacksize() failure:%s\n",strerror(errno));
		goto CleanUp;
	}

	if(pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_DETACHED))
	{
		printf("pthread_attr_setdetachstate() falure:%s\n",strerror(errno));
		goto CleanUp;
	}

	if(pthread_create(thread_id,&thread_attr,thread_workerbody,thread_arg))
	{
		printf("Create thread failure:%s\n",strerror(errno));
		goto CleanUp;
	}

	rv = 0;

CleanUp:
	pthread_attr_destroy(&thread_attr);
	return rv;
}



void *thread_worker(void *ctx)
{
	int                     rv=-1;
	int                     client_fd;
	char                    buf[1024];
	char                    devid[8];
	float                   temp;
	char                    timep[32];
	char                    *tmp=NULL;

	if(!ctx)
	{
		printf("Invaild input arguments in %s()\n",__FUNCTION__);
		pthread_exit(NULL);
	}

	client_fd=(int)ctx;

	printf("Child thread start to commuciate with socket client...\n");
	printf("\n");


	while(1)
	{
		memset(buf,0,sizeof(buf));
		rv=read(client_fd,buf,sizeof(buf));
		if(rv<0)
		{
			printf("read data from client failure:%s\n",strerror(errno));
			close(client_fd);
			pthread_exit(NULL);
		}
		else if(rv==0)
		{
			printf("Disconnect");
			close(client_fd);
			pthread_exit(NULL);
		}

		memset(devid,0,sizeof(devid));
		temp = 0.0;
		parser_json(buf,devid,8,&temp,timep);

		//              printf("This is thread_worker!\n ");
		printf("devid:%s\ntime:%s\ntemp:%.3f °C\n",devid,timep,temp);

		if((tmp=strstr(timep,"\n")))
		{
			*tmp = '\0';
		}

		insert_mysql(devid,timep,&temp);
		printf("------Successfully saved the data to the databases!------\n");


		rv=write(client_fd,buf,sizeof(buf));
		if(rv<0)
		{
			printf("'write ' failure:%s\n",strerror(errno));
			close(client_fd);
			pthread_exit(NULL);
		}

		printf("\n");
	}

}



